package gamebackend;

/**
 * Maintains two Fliers and directs them to fly to
 * a target while staying close to each other.
 * 
 * @author Jonathan Caddey
 */
public class TogetherFlier extends AbstractFlier {
	private final Flier my_first;
	private final Flier my_second;
	private boolean my_firstFaster;
	private final double my_difference;
	
	/**
	 * @param the_first
	 * @param the_second
	 * @param the_difference don't use 0, there's no point.
	 */
	public TogetherFlier(final Flier the_first, final Flier the_second, final double the_difference) {
		my_first = the_first;
		my_second = the_second;
		my_firstFaster = true;
		my_difference = the_difference;
	}
	
	
	

	@Override
	public void step(double the_yChange) {
		my_first.step(the_yChange);
		my_second.step(the_yChange);
		
		// the faster flier should aim to be my_difference closer to the target than the slower.
		Flier faster = my_firstFaster ? my_first : my_second;
		Flier slower = !my_firstFaster ? my_first : my_second;
		faster.setTarget(slower.getPosition() + my_difference * Math.signum(getTarget() - slower.getPosition()));
		
		// check to make sure the slower path isn't actually too much closer to the target than the faster
		final double difference = faster.getPosition() - slower.getPosition();
		if (Math.abs(difference) > my_difference * 1.2 + 5
				&& (Math.signum(difference) * Math.signum(getTarget() - faster.getPosition()) < 0)) {
			// swap slower and faster
			my_firstFaster = !my_firstFaster;
			faster.setTarget(getTarget() - my_difference / 2 * Math.signum(getTarget() - faster.getPosition()));
		}
	}

	@Override
	public void setTarget(double the_target) {
		super.setTarget(the_target);
		double difference = my_difference / 2;
		
		if (my_first.getPosition() < my_second.getPosition()) {
			difference *= -1;
		}
		my_first.setTarget(the_target + difference);
		my_second.setTarget(the_target - difference);
	}


	@Override
	public boolean isAtTarget() {
		return Math.abs(getPosition() - getTarget()) < my_difference / 2 + 5;
	}

	@Override
	public Flier getChild() {
		return null;
	}
	
	@Override
	public double getPosition() {
		return (my_first.getPosition() + my_second.getPosition()) / 2;
	}

}
